<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\AdminLoginLog;
use \think\Request;
use think\facade\View;
use app\common\model\Admin;
use app\common\model\AdminQuanxian;
use app\common\model\AdminOperationLog;
use app\common\model\AdminGoodsLog;
use app\common\model\GoodsList;
use think\facade\Db;

class Admins extends Base
{
    // 管理员列表
    public function admin()
    {
        $username = trim(input('get.username'));
        $nickname = trim(input('get.nickname'));
        $whe = array();
        if (!empty($username)) {
            $whe[] = ['username', 'like', "%" . $username . "%"];
        }
        if (!empty($nickname)) {
            $whe[] = ['nickname', 'like', "%" . $nickname . "%"];
        }
        $field = "*";
        $order = "id asc";
        $data = Admin::getList($whe, $field, $order, 100);
        foreach ($data['list'] as $k => $v) {
            $qx_name = AdminQuanxian::where(['id' => $v['qid']])->value('title');
            $data['list'][$k]['qx_name'] = $qx_name ? $qx_name : '最高权限';
        }
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch('Admins/admin');
    }

    // 添加管理员
    public function admin_add()
    {
        if (!request()->isPost()) {
            $quanxian = AdminQuanxian::field('id,title')->order('id asc')->select();
            View::assign('quanxian', $quanxian);
            return View::fetch('Admins/admin_add');
        } else {
            if ($this->admin_id != 1) {
                return $this->err('权限不足');
            }
            $data = input('post.');
            if (empty($data['username'])) {
                return $this->err('请输入账号');
            }
            if (empty($data['nickname'])) {
                return $this->err('请输入姓名');
            }
            if (empty($data['password'])) {
                return $this->err('请输入密码');
            }
            if (empty($data['repassword'])) {
                return $this->err('请输入重复密码');
            }
            if (strlen($data['username']) < 5 || strlen($data['username']) > 16) {
                return $this->err('账号长度请输入5-16位');
            }
            if (mb_strlen($data['nickname']) < 2 || mb_strlen($data['nickname']) > 10) {
                return $this->err('姓名长度请输入2-10位');
            }
            if (strlen($data['password']) < 6 || strlen($data['password']) > 16) {
                return $this->err('密码长度请输入6-16位');
            }
            if ($data['password'] !== $data['repassword']) {
                return $this->err('两次密码输入不一致');
            }
            $is_username = Admin::where(['username' => $data['username']])->find();
            if ($is_username) {
                return $this->err('账号已存在');
            }
            unset($data['repassword']);
            $data['password'] = admin_md5($data['password']);
            $data['addtime'] = time();
            $data['admin_id'] = $this->admin_id;
            $data['random'] = mt_rand(100000, 999999);
            $result = Admin::insert($data);
            if ($result) {
                return $this->succ('添加成功');
            } else {
                return $this->err('添加失败');
            }
        }
    }

    // 修改管理员
    public function admin_edit()
    {
        if (!request()->isPost()) {
            $id = request()->param('id');
            $admin = Admin::where(['id' => $id])->find();
            if (!$admin) {
                $this->err('参数错误');
            }
            $quanxian = AdminQuanxian::field('id,title')->order('id asc')->select();
            View::assign('quanxian', $quanxian);
            View::assign('admin', $admin);
            return View::fetch('Admins/admin_edit');
        } else {
            if ($this->admin_id != 1) {
                return $this->err('权限不足');
            }
            $data = input('post.');
            if (empty($data['id'])) {
                return $this->err('请求参数错误');
            }
            $admin = Admin::where(['id' => $data['id']])->find();
            if (!$admin) {
                $this->err('请求参数错误1');
            }
            #验证账号
            $is_username = Admin::where(['username' => $data['username']])
                ->where('id', '<>', $admin['id'])
                ->find();
            if ($is_username) {
                return $this->err('账号已存在');
            }
            if (empty($data['username'])) {
                return $this->err('请输入账号');
            }
            if (empty($data['nickname'])) {
                return $this->err('请输入姓名');
            }
            if (strlen($data['username']) < 5 || strlen($data['username']) > 16) {
                return $this->err('账号长度请输入5-16位');
            }
            if (mb_strlen($data['nickname']) < 2 || mb_strlen($data['nickname']) > 10) {
                return $this->err('姓名长度请输入2-10位');
            }
            if ($data['password'] || $data['repassword']) {
                if (empty($data['password'])) {
                    return $this->err('请输入密码');
                }
                if (empty($data['repassword'])) {
                    return $this->err('请输入重复密码');
                }
                if (strlen($data['password']) < 6 || strlen($data['password']) > 16) {
                    return $this->err(0, '密码长度请输入6-16位');
                }
                if ($data['password'] !== $data['repassword']) {
                    return $this->err('两次密码输入不一致');
                }
                unset($data['repassword']);
                $data['password'] = admin_md5($data['password']);
            } else {
                unset($data['password']);
                unset($data['repassword']);
            }
            $data['update_time'] = time();
            $data['random'] = mt_rand(100000, 999999);
            unset($data['id']);
            $result = Admin::where(['id' => $admin['id']])->update($data);
            if ($result) {
                return $this->succ('修改成功');
            } else {
                return $this->err('修改失败');
            }
        }
    }

    /**
     * 禁用 启用
     */
    public function admin_disable()
    {
        if ($this->admin_id != 1) {
            return $this->err('权限不足');
        }
        $id = request()->param('id');
        $info = Admin::where(['id' => $id])->find();
        if (!$info) {
            return $this->err('请求参数错误');
        }
        if ($info['id'] == $this->admin_id) {
            return $this->err('无法对自己的账号进行此操作');
        }
        if ($info['status'] == 0) {
            $data['status'] = 1;
            $data['update_time'] = time();
        } elseif ($info['status'] == 1) {
            $data['status'] = 0;
            $data['update_time'] = time();
        }
        $result = Admin::where(['id' => $id])->update($data);
        if ($result) {
            return $this->succ('操作成功');
        } else {
            return $this->err('操作失败');
        }

    }

    //删除
    public function admin_delete()
    {
        if ($this->admin_id != 1) {
            return $this->err('权限不足');
        }
        $id = request()->param('id');
        $info = Admin::where(['id' => $id])->find();
        if (!$info) {
            return $this->err('请求参数错误');
        }
        if ($info['id'] == $this->admin_id) {
            return $this->err('无法对自己的账号进行此操作');
        }
        $result = Admin::where(['id' => $id])->delete();
        if ($result) {
            return $this->succ('操作成功');
        } else {
            return $this->err('操作失败');
        }
    }


    //登录日志
    public function admin_login_log()
    {
        $username = trim(input('get.username'));
        $addtime = trim(input('get.addtime'));
        $whe = [];
        #账号
        if ($username) {
            $a_id = Admin::field('id')->where('username', $username)->value('id');
            $whe[] = ['a_id', '=', $a_id];
        }

        #登录时间
        if ($addtime) {
            $time = explode(' - ', $addtime);
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]) - 1;
            if ($start_time > $end_time) {
                $this->err('开始时间不能大于结束时间');
            }
            $whe[] = ['addtime', 'BETWEEN', array($start_time, $end_time)];
        }
        $field = "*";
        $order = "id desc";
        $data = AdminLoginLog::getList($whe, $field, $order, 10);
        foreach ($data['list'] as $k => &$v) {
            $username = Admin::field('username')->where(['id' => $v['a_id']])->value('username');
            $v['username'] = $username;
            $v['ip'] = long2ip($v['ip']);
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
        }
        View::assign("list", $data['list']);
        View::assign("count", $data['count']);
        View::assign("page", $data['page']);
        return View::fetch('Admins/admin_login_log');
    }

    // 角色列表
    public function admin_quanxian()
    {
        $whe = array();
        $list = AdminQuanxian::where($whe)->select();
        $count = count($list);
        View::assign('list', $list);
        View::assign('adminid', $this->admin_id);
        View::assign('count', $count);
        return View::fetch('Admins/admin_quanxian');
    }

    // 添加管理员
    public function admin_quanxian_add()
    {
        if (!request()->isPost()) {
            $menu = config('menu');
            View::assign('menu', $menu);
            return View::fetch('Admins/admin_quanxian_add');
        } else {
            $data = input('post.');
            if (empty($data['title'])) {
                return $this->err('请输入角色名称');
            }
            if (empty($data['describe'])) {
                return $this->err('请输入角色描述');
            }
            if (empty($data['quanxian'])) {
                return $this->err('请选择权限');
            }
            $data['addtime'] = time();
            $data['admin_id'] = $this->admin_id;
            $data['quanxian'] = implode(',', $data['quanxian']);
            $result = AdminQuanxian::insert($data);
            if ($result) {
                return $this->succ('添加成功');
            } else {
                return $this->err('添加失败');
            }
        }
    }

    // 修改管理员
    public function admin_quanxian_edit()
    {

        if (!request()->isPost()) {
            $id = request()->param('id');
            $info = AdminQuanxian::where(array('id' => $id))->find();
            if (!$info) {
                $this->err('参数错误');
            }
            $menu = config('menu');
            $quanxian = explode(',', $info['quanxian']);
            foreach ($menu as $k => $v) {
                foreach ($v['son'] as $s => $so) {
                    $name = $so['name'];
                    if (in_array($name, $quanxian)) {
                        $menu[$k]['son'][$s]['check'] = 1;
                        $menu[$k]['pcheck'] = 1;
                    } else {
                        $menu[$k]['son'][$s]['check'] = 2;
                        if (empty($menu[$k]['pcheck'])) {
                            $menu[$k]['pcheck'] = 2;
                        }
                    }
                }
            }
            View::assign('info', $info);
            View::assign('menu', $menu);
            return View::fetch('Admins/admin_quanxian_edit');
        } else {
            $data = input('post.');
            if (empty($data['id'])) {
                return $this->err('参数错误1');
            }
            $info_u = AdminQuanxian::where(['id' => $data['id']])->find();
            if (!$info_u) {
                return $this->err('参数错误2');
            }
            if (empty($data['title'])) {
                return $this->err('请输入角色名称');
            }
            if (empty($data['describe'])) {
                return $this->err('请输入角色描述');
            }
            if (empty($data['quanxian'])) {
                return $this->err('请选择权限');
            }
            unset($data['id']);
            $data['update_time'] = time();
            $data['admin_id'] = $this->admin_id;
            $data['quanxian'] = implode(',', $data['quanxian']);
            $result = AdminQuanxian::where(['id' => $info_u['id']])->update($data);
            if ($result) {
                return $this->succ('编辑成功');
            } else {
                return $this->err('编辑失败');
            }
        }
    }

    // 删除
    public function admin_quanxian_del()
    {
        $id = request()->param('id/d');
        $quanxian = AdminQuanxian::where(array('id' => $id))->field('id')->find();
        if (!$quanxian) {
            return $this->err('数据不存在');
        }
        $is_use = Admin::where(array('qid' => $id))->field('id')->find();
        if ($is_use) {
            return $this->err('该角色下有管理员正在使用，无法删除');
        }
        $result = AdminQuanxian::where('id', $id)->delete();
        if ($result) {
            return $this->succ('删除成功');
        } else {
            return $this->err('网络繁忙，请稍后');
        }

    }
    public function admin_operationlog(){
        
        $username = request()->param('username');
        $were = [];
        if(!empty($username)){
           $a_id = Admin::where('username','like',"$username%")->value('id');
           $were['a_id'] =$a_id;
        }
        $data = AdminOperationLog::getList($were, '*', 'id desc', $this->page);
        foreach($data['list'] as &$item){
            $item['ad_name'] = Admin::where(array('id' => $item['a_id']))->value('username');
        }
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch('Admins/adminoperationlog');
    }
    
    public function admin_goods_log(){
        $username = trim(input('get.username'));
        $addtime = trim(input('get.addtime'));
        $whe = [];
        #账号
        if ($username) {
            $a_id = Admin::field('id')->where('username', $username)->value('id');
            $whe[] = ['admin_id', '=', $a_id];
        }

        #登录时间
        if ($addtime) {
            $time = explode(' - ', $addtime);
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]) - 1;
            if ($start_time > $end_time) {
                $this->err('开始时间不能大于结束时间');
            }
            $whe[] = ['addtime', 'BETWEEN', array($start_time, $end_time)];
        }
//        $whe[] = ['content','<>','[]'];
        $field = "*";
        $order = "id desc";
        $data = AdminGoodsLog::getList($whe, $field, $order, 10);
        foreach ($data['list'] as $k => &$v) {
            $username = Admin::field('username')->where(['id' => $v['a_id']])->value('username');
            $v['username'] = $username;
            $v['ip'] = long2ip($v['ip']);
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            $goods = \app\common\model\Goods::find($v['goods_id']);
            if($goods['type'] == 1){
                $v['type_name'] = '一番赏';
            }else if($goods['type'] == 2){
                $v['type_name'] = '无限赏';
            }else if($goods['type'] == 3){
                $v['type_name'] = '擂台赏';
            }else if($goods['type'] == 5){
                $v['type_name'] = '积分赏';
            }else if($goods['type'] ==6){
                $v['type_name'] = '全局赏';
            }else if($goods['type'] ==7){
                $v['type_name'] = '福利盲盒';
            } else if($goods['type'] ==8){
                $v['type_name'] = '领主赏';
            } else if($goods['type'] ==9){
                $v['type_name'] = '连击赏';
            }else{
                $v['type_name'] = '';
            }
            $v['goods_name'] = $goods['title'];
            $v['goods_list_name'] = GoodsList::where('id',$v['goods_list_id'])->value('title');
           
            $new_data = json_decode($v['new_data'],true);
        
            $old_data = json_decode($v['original_data'],true);
            if ($v['goods_list_id'] > 0){
                $html = '盒子:【'.$v['goods_name'].'】商品:【'.$v['goods_list_name'].'】';
            }else{
                $html = '盒子:【'.$v['goods_name'].'】';
            }
            foreach ($new_data as $key=>$value){
                
                if (isset($old_data[$key]) && $old_data[$key] != $value){
                    if ($v['goods_list_id'] > 0){
//                        dd(11);
                        if ($this->goods_list_title($key)){
                            // if(isset($old_data['update_time'])){
                            //     $old_data['update_time'] = strtotime('Y-m-d H:i:s',$old_data['update_time']);
                            // }
                            // if(isset($value['update_time'])){
                            //     $value['update_time'] = strtotime('Y-m-d H:i:s',$value['update_time']);
                            // }
                            $html .= '【修改前'.$this->goods_list_title($key).':'.$old_data[$key].'---修改后：'.$this->goods_list_title($key).':'.$value.'】';
                        }

                    }else{
                        if ($this->goods_title($key)){
                            $html .= '【修改前'.$this->goods_title($key).':'.$old_data[$key].'---修改后：'.$this->goods_title($key).':'.$value.'】';
                        }
//                        dd();
//                        $html .= '【修改前'.$this->goods_title($key).':'.$old_data[$key].'---修改后：'.$this->goods_title($key).':'.$value.'】';
                    }
                }
            }
            $v['html'] = $html;
        }
        View::assign("list", $data['list']);
        View::assign("count", $data['count']);
        View::assign("page", $data['page']);
        return View::fetch('Admins/admin_goods_log');
    }
    
    public function goods_title($key){
//            dd($key);
        $arr = [];
        $arr['title'] = '标题';
        $arr['price'] = '价格';
        $arr['stock'] = '套数';
        $arr['prize_num'] = '全局发数';
        $arr['status'] = '状态';
        $arr['sort'] = '排序';
        $arr['show_is'] = '首页显示';
        $arr['update_time'] = '修改时间';
        $arr['shang_id'] = '赏title';
        $arr['money'] = '';
        $arr['look_pro'] = '概率';
        $arr['is_shou_zhe'] = '首抽五折';
        $arr['coupon_is'] = '发券开关';
        $arr['integral_is'] = '发积分开关';
        $arr['rage_is'] = '怒气值开关';
        $arr['rage'] = '怒气值';
        $arr['lian_ji_num'] = '连击赏连击次数';
        $arr['lian_ji_shang_id'] = '连击赏赏id';
        $arr['lingzhu_is'] = '领主开关';
        $arr['lingzhu_fan'] = '领主每发返';
        $arr['lingzhu_shang_id'] = '请选择抽中领主';
        if (isset($arr[$key])){
            return $arr[$key];
        }
        return false;
    }
    
    public function goods_list_title($key){
//        dd(11);
        $arr = [];
        $arr['title'] = '标题';
        $arr['stock'] = '库存';
        $arr['price'] = '价格';
        $arr['money'] = '回收价';
        $arr['real_pro'] = '概率';
//        $arr['look_pro'] = '概率';
        $arr['shang_id'] = '赏id';
        $arr['update_time'] = '修改时间';
        if (isset($arr[$key])){
            return $arr[$key];
        }
        return false;
    }
    
}